"use client";

import { useState } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { signIn } from "next-auth/react";
import { Alert, Button, Card, Form, Input, Space, Typography, App } from "antd";
import { LockOutlined, UserOutlined } from "@ant-design/icons";
import Link from "next/link";

interface LoginFormData {
  email: string;
  password: string;
}

export default function LoginForm() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const [loading, setLoading] = useState(false);
  const { message } = App.useApp();

  const callbackUrl = searchParams.get("callbackUrl");
  const decodedCallbackUrl = callbackUrl ? decodeURIComponent(callbackUrl) : "/dashboard";

  const onFinish = async (values: LoginFormData) => {
    try {
      setLoading(true);
      
      const result = await signIn("credentials", {
        email: values.email,
        password: values.password,
        redirect: false,
      });

      if (result?.error) {
        message.error(result.error === "CredentialsSignin" ? "邮箱或密码错误" : result.error);
        return;
      }

      message.success("登录成功");
      // 使用 window.location 进行跳转以确保完全刷新
      window.location.href = decodedCallbackUrl;
    } catch (error) {
      console.error(error);
      message.error("登录过程中发生错误");
    } finally {
      setLoading(false);
    }
  };

  return (
    <Card style={{ width: 400 }}>
      <Space direction="vertical" size="large" style={{ width: "100%" }}>
        <Typography.Title level={2} style={{ textAlign: "center", marginBottom: 0 }}>
          登录
        </Typography.Title>

        <Form
          name="login"
          onFinish={onFinish}
          autoComplete="off"
          layout="vertical"
        >
          <Form.Item
            name="email"
            rules={[
              { required: true, message: "请输入邮箱" },
              { type: "email", message: "请输入有效的邮箱地址" },
            ]}
          >
            <Input prefix={<UserOutlined />} placeholder="邮箱" />
          </Form.Item>

          <Form.Item
            name="password"
            rules={[{ required: true, message: "请输入密码" }]}
          >
            <Input.Password prefix={<LockOutlined />} placeholder="密码" />
          </Form.Item>

          <Form.Item>
            <Button type="primary" htmlType="submit" block loading={loading}>
              登录
            </Button>
          </Form.Item>
        </Form>

        <Typography.Text style={{ textAlign: "center", display: "block" }}>
          还没有账号？{" "}
          <Link 
            href={`/register${callbackUrl ? `?callbackUrl=${callbackUrl}` : ""}`}
          >
            立即注册
          </Link>
        </Typography.Text>
      </Space>
    </Card>
  );
} 